<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useRentalStore } from "@/stores/rental";
import { getCarDetail } from "@/api/car";
import { createOrder } from "@/api/order";
import { showToast, showDialog } from "vant";
import dayjs from "dayjs";

const route = useRoute();
const router = useRouter();
const rentalStore = useRentalStore();
const carDetail = ref(null);
const loading = ref(true);
const selectedReturnCity = ref("");
const additionalServices = ref([]);
const showReturnCityPicker = ref(false);

// 服务选项
const serviceOptions = [
  { text: "GPS导航", value: "GPS导航", price: 30 },
  { text: "儿童座椅", value: "儿童座椅", price: 50 },
];

// 格式化城市数据为picker需要的格式
const returnCityColumns = computed(() => {
  if (!carDetail.value?.returnCities) return [];
  return carDetail.value.returnCities.map((city) => ({
    text: city,
    value: city,
  }));
});

// 获取车辆详情
const fetchCarDetail = async () => {
  try {
    const response = await getCarDetail(route.query.carId);
    carDetail.value = response;
    // 默认选择第一个可还车城市
    if (response.returnCities?.length) {
      selectedReturnCity.value = response.returnCities[0];
    }
  } catch (error) {
    showToast("获取车辆信息失败");
  } finally {
    loading.value = false;
  }
};

// 计算租期天数
const rentalDays = computed(() => {
  const start = dayjs(rentalStore.pickupDate);
  const end = dayjs(rentalStore.returnDate);
  return end.diff(start, "day");
});

// 计算租车费用
const rentalFee = computed(() => {
  if (!carDetail.value) return 0;
  return carDetail.value.dailyRate * rentalDays.value;
});

// 计算附加服务费用
const additionalServicesFee = computed(() => {
  return additionalServices.value.reduce((total, service) => {
    const serviceOption = serviceOptions.find(
      (option) => option.value === service
    );
    return total + (serviceOption?.price || 0);
  }, 0);
});

// 保险费用
const insuranceFee = 50;

// 押金
const deposit = 2000;

// 计算总费用（不含押金）
const totalAmount = computed(() => {
  return rentalFee.value + additionalServicesFee.value + insuranceFee;
});

// 选择城市
const onSelectReturnCity = (value) => {
  selectedReturnCity.value = value.text || value;
  showReturnCityPicker.value = false;
};

// 提交订单
const submitOrder = async () => {
  try {
    if (!selectedReturnCity.value) {
      showToast("请选择还车城市");
      return;
    }

    const orderData = {
      carId: route.query.carId,
      startTime: dayjs(rentalStore.pickupDate).format("YYYY-MM-DDTHH:mm:ssZ"),
      endTime: dayjs(rentalStore.returnDate).format("YYYY-MM-DDTHH:mm:ssZ"),
      pickupLocation: rentalStore.pickupCity,
      returnLocation: selectedReturnCity.value,
      additionalServices: additionalServices.value,
      totalAmount: totalAmount.value,
      rentalFee: rentalFee.value,
      insuranceFee: insuranceFee,
      deposit: deposit,
    };

    await showDialog({
      title: "确认订单",
      message: `确认支付押金 ${deposit} 元并提交订单吗？`,
      showCancelButton: true,
    });

    const response = await createOrder(orderData);
    showToast("订单创建成功");
    router.push("/order");
  } catch (error) {
    if (error.message === "cancel") return;
    showToast(error.message || "创建订单失败");
  }
};

onMounted(() => {
  if (!route.query.carId) {
    showToast("缺少必要参数");
    router.back();
    return;
  }
  fetchCarDetail();
});
</script>

<template>
  <div class="order-confirm">
    <van-nav-bar
      title="确认订单"
      left-arrow
      @click-left="router.back()"
      fixed
      placeholder
    />

    <van-loading v-if="loading" class="loading" />

    <template v-else-if="carDetail">
      <!-- 车辆信息 -->
      <div class="car-info">
        <van-image
          :src="carDetail.coverImage"
          fit="cover"
          width="120"
          height="80"
          radius="4"
        />
        <div class="car-details">
          <h3>{{ carDetail.brand }} {{ carDetail.model }}</h3>
          <div class="tags">
            <van-tag plain type="primary">{{ carDetail.type }}</van-tag>
            <van-tag plain type="warning">{{ carDetail.level }}</van-tag>
          </div>
        </div>
      </div>

      <!-- 租车信息 -->
      <van-cell-group inset class="rental-info">
        <van-cell title="取车时间" :value="rentalStore.pickupDate" />
        <van-cell title="还车时间" :value="rentalStore.returnDate" />
        <van-cell title="租期" :value="`${rentalDays}天`" />
        <van-cell title="取车城市" :value="rentalStore.pickupCity" />
        <van-cell
          title="还车城市"
          :value="selectedReturnCity || '请选择城市'"
          is-link
          @click="showReturnCityPicker = true"
        />
      </van-cell-group>

      <!-- 附加服务 -->
      <van-cell-group inset class="services">
        <van-cell title="附加服务">
          <template #value>
            <van-checkbox-group v-model="additionalServices">
              <div
                v-for="service in serviceOptions"
                :key="service.value"
                class="service-item"
              >
                <van-checkbox :name="service.value" shape="square">
                  {{ service.text }}
                  <span class="service-price">+{{ service.price }}元</span>
                </van-checkbox>
              </div>
            </van-checkbox-group>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 费用明细 -->
      <van-cell-group inset class="fee-details">
        <van-cell title="车辆租金" :value="`¥${rentalFee}`" />
        <van-cell title="保险费用" :value="`¥${insuranceFee}`" />
        <van-cell
          title="附加服务费"
          :value="`¥${additionalServicesFee}`"
          v-if="additionalServicesFee > 0"
        />
        <van-cell title="押金" :value="`¥${deposit}`" />
        <van-cell
          title="费用合计"
          :value="`¥${totalAmount}`"
          value-class="total-amount"
        >
          <template #label>
            <span class="deposit-note">另需支付押金¥{{ deposit }}</span>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 底部提交按钮 -->
      <div class="submit-bar">
        <div class="price-info">
          <span class="label">总计：</span>
          <span class="amount">¥{{ totalAmount }}</span>
        </div>
        <van-button type="primary" block @click="submitOrder">
          提交订单
        </van-button>
      </div>

      <!-- 修改还车城市选择弹出层 -->
      <van-popup
        v-model:show="showReturnCityPicker"
        position="bottom"
        v-if="carDetail && carDetail.returnCities?.length"
      >
        <van-picker
          show-toolbar
          title="选择还车城市"
          :columns="returnCityColumns"
          @confirm="onSelectReturnCity"
          @cancel="showReturnCityPicker = false"
        >
          <template #title>选择还车城市</template>
        </van-picker>
      </van-popup>
    </template>
  </div>
</template>

<style scoped lang="scss">
.order-confirm {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 80px;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.car-info {
  margin: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 16px;

  .car-details {
    flex: 1;

    h3 {
      margin: 0 0 8px;
      font-size: 16px;
      font-weight: bold;
    }

    .tags {
      display: flex;
      gap: 8px;
    }
  }
}

.rental-info,
.services,
.fee-details {
  margin: 16px;
}

.service-item {
  margin: 8px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .service-price {
    margin-left: 8px;
    color: #999;
    font-size: 12px;
  }
}

.deposit-note {
  color: #999;
  font-size: 12px;
}

.total-amount {
  color: #f44336 !important;
  font-weight: bold;
  font-size: 16px;
}

.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;

  .price-info {
    .label {
      font-size: 14px;
      color: #666;
    }

    .amount {
      font-size: 20px;
      font-weight: bold;
      color: #f44336;
    }
  }

  .van-button {
    width: 120px;
    border-radius: 8px;
  }
}

// 暗黑模式适配
@media (prefers-color-scheme: dark) {
  .car-info,
  .submit-bar {
    background: #1c1c1e;
  }
}
</style> 